package com.web.activiti.service.Impl;

import com.web.activiti.mapper.LeavebillMapper;
import com.web.activiti.pojo.Employee;
import com.web.activiti.pojo.Leavebill;
import com.web.activiti.service.WorkFlowService;
import com.web.activiti.utils.Contants;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;


/**
 * 请假流程
 */
@Service
public class WorkFlowServiceImpl implements WorkFlowService {
    @Autowired
    private RepositoryService repositoryService;  //流程定义
    @Autowired
    private RuntimeService runtimeService;        //流程实例
    @Autowired
    private TaskService taskService;              //活动任务节点
    @Autowired
    private LeavebillMapper leavebillMapper;        //请假单的映射
    @Override
    /**
     * 部署流程zip
     */
    public void delployProcess (String processName , InputStream resourceFile) {
        ZipInputStream zipInput=new ZipInputStream(resourceFile);
        Deployment deploy = this.repositoryService.createDeployment().name(processName)
                .addZipInputStream(zipInput)
                .deploy();
    }


    /**
     * 查询所有的发布的流程信息
     * @return
     */
    @Override
    public List<Deployment> findAllDeployments () {
        return repositoryService.createDeploymentQuery().list();
    }

    /**
     * 查找所有的流程定义
     * @return
     */
    @Override
    public List<ProcessDefinition> findAllProcessDefinitions () {
        return repositoryService.createProcessDefinitionQuery().list();
    }

    /**
     * 通过任务id查询请假单
     * @param taskId
     * @return
     */
    @Override
    public Leavebill findBillByTask (String taskId) {
        Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
        ProcessInstance pi=runtimeService.createProcessInstanceQuery()
                .processInstanceId(task.getProcessInstanceId()).singleResult();

        String businessKey = pi.getBusinessKey();
        System.out.println(businessKey);
        String id = businessKey.split("\\.")[1];
        Leavebill bill = leavebillMapper.selectByPrimaryKey(Long.parseLong(id));
        return bill;
    }

    /**
     * 请假表单提交上来的数据，插入新的请假单
     * @param leavebill
     * @param employee
     */
    @Override
    public void saveStartProcess (Leavebill leavebill , Employee employee) {
        //1.保存请假单到数据库
        leavebill.setLeavedate(new Date());
        leavebill.setState(1);
        leavebill.setUserId(employee.getId());
        leavebillMapper.insert(leavebill);

        //2.启动流程实例
        String key= Contants.LEAVEBILL_KEY;
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", employee.getName());
        String BUSSINESS_KEY=Contants.LEAVEBILL_KEY+"." +leavebill.getId();
        runtimeService.startProcessInstanceByKey(key,BUSSINESS_KEY,map);
    }

    /**
     * 通过id查看出所有的任务
     * @param assignee
     * @return
     */
    @Override
    public List<Task> findTaskListByUserId (String assignee) {
        return taskService.createTaskQuery().taskAssignee(assignee).list();
    }

    /**
     * 通过id查看该请假条的批注
     * @param taskId
     * @return
     */
    @Override
    public List<Comment> findCommentList (String taskId) {
        System.out.println(taskId);
        Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
        List<Comment> comments = taskService.getProcessInstanceComments(task.getProcessInstanceId());
        return comments;
    }

    /**
     * 用于将提交上来的批注保存到数据库中
     * @param id
     * @param taskId
     * @param comment
     * @param name
     */
    @Override
    public void saveSubmitTask (long id , String taskId , String comment , String name) {
        //加批注
        Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstanceId = task.getProcessInstanceId();
        //加当前任务的审核人
        Authentication.setAuthenticatedUserId(name);
        taskService.addComment(taskId, processInstanceId, comment);
        //流程要结束，往前推进
        taskService.complete(taskId);
        //如果流程实例结束，修改业务表的状态
        ProcessInstance pi=runtimeService.createProcessInstanceQuery()
                .processInstanceId(task.getProcessInstanceId()).singleResult();
        if (pi==null){
            Leavebill leavebill=leavebillMapper.selectByPrimaryKey(id);
            leavebill.setState(2);
            leavebillMapper.updateByPrimaryKey(leavebill);
        }
    }
}
